<template>
  <div class="storage-overview">
    <!-- 存储服务概览标题 -->
    <div class="overview-header">
      <h2>存储服务概览</h2>
    </div>
    
    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <a-row :gutter="[20, 20]">
        <!-- 存储容量卡片 -->
        <a-col :span="6">
          <div class="stat-card storage-card">
            <div class="stat-content">
              <div>
                <div class="stat-value">{{storageData.total}}</div>
                <div class="stat-label">总存储容量</div>
                <div class="progress-bar">
                  <div class="progress-fill storage-progress" :style="{ width: storageData.usagePercent + '%' }"></div>
                </div>
              </div>
              <div class="stat-detail">
                <div class="detail-row">
                  <span class="detail-label">已用: {{ storageData.capacity   }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">可用: {{ storageData.available }}</span>
                </div>
              </div>
            </div>
          </div>
        </a-col>
        
        <!-- CPU使用率卡片 -->
        <a-col :span="6">
          <div class="stat-card cpu-card">
            <div class="stat-content">
              <div>
                <div class="stat-value">{{ cpuData.usage }}%</div>
                <div class="stat-label">CPU使用率</div>
                <div class="progress-bar">
                  <div class="progress-fill cpu-progress" :style="{ width: cpuData.usagePercent + '%' }"></div>
                </div>
              </div>
              <div class="stat-detail">
                <div class="detail-row">
                  <span class="detail-label">峰值: {{ cpuData.peak }}%</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">平均: {{ cpuData.average }}%</span>
                </div>
              </div>
            </div>
          </div>
        </a-col>
        
        <!-- 备份数据卡片 -->
        <a-col :span="6">
          <div class="stat-card backup-card">
            <div class="stat-content">
              <div>
                <div class="stat-value">{{ backupData.count }}</div>
                <div class="stat-label">备份数据</div>
                <div class="progress-bar">
                  <div class="progress-fill backup-progress" :style="{ width: backupData.progressPercent + '%' }"></div>
                </div>
              </div>
              <div class="stat-detail">
                <div class="detail-row">
                  <span class="detail-label">全量备份: {{ backupData.full }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">其他备份: {{ backupData.other }}</span>
                </div>
              </div>
            </div>
          </div>
        </a-col>
        
        <!-- 通知告警卡片 -->
        <a-col :span="6">
          <div class="stat-card notification-card">
            <div class="stat-content">
              <div>
                <div class="stat-value">{{ notificationData.count }}</div>
                <div class="stat-label">通知告警</div>
                <div class="progress-bar">
                  <div class="progress-fill notification-progress" :style="{ width: notificationData.progressPercent + '%' }"></div>
                </div>
              </div>
              <div class="stat-detail">
                <div class="detail-row">
                  <span class="detail-label">通知: {{ notificationData.notice }}</span>
                </div>
                <div class="detail-row">
                  <span class="detail-label">告警: {{ notificationData.alert }}</span>
                </div>
              </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
    
    <!-- 趋势图表区域 -->
    <div class="chart-section">
      <div class="chart-card">
        <div class="chart-header">
          <h3>核心功能监控</h3>
          <div class="chart-controls">
            <span class="time-range">24小时</span>
            <a-button size="small" type="text" class="refresh-btn" @click="refreshTrend">
              <ReloadOutlined />
            </a-button>
          </div>
        </div>
        <div class="chart-container">
          <div class="chart-content">
            <div class="chart-legend">
              <div class="legend-item">
                <span class="legend-dot iops"></span>
                <span class="legend-text">IOPS</span>
              </div>
              <div class="legend-item">
                <span class="legend-dot throughput"></span>
                <span class="legend-text">吞吐量</span>
              </div>
            </div>
            <div class="chart-area">
              <svg width="100%" height="220" viewBox="0 0 700 220" class="performance-chart">
                <!-- 网格线 -->
                <defs>
                  <pattern id="grid" width="50" height="40" patternUnits="userSpaceOnUse">
                    <path d="M 50 0 L 0 0 0 40" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="1"/>
                  </pattern>
                  <linearGradient id="throughputGradient" x1="0%" y1="0%" x2="0%" y2="100%">
                    <stop offset="0%" style="stop-color:#00CFFD;stop-opacity:0.3" />
                    <stop offset="100%" style="stop-color:#00CFFD;stop-opacity:0" />
                  </linearGradient>
                </defs>
                <rect width="100%" height="100%" fill="url(#grid)" />
                
                <!-- IOPS曲线（动态） -->
                <path :d="iopsPath" stroke="#FFFFFF" stroke-width="2" fill="none"/>
                
                <!-- 吞吐量曲线和填充（动态） -->
                <path :d="throughputAreaPath" fill="url(#throughputGradient)"/>
                <path :d="throughputPath" stroke="#00CFFD" stroke-width="2" fill="none"/>
                
                <!-- 动态Y轴标签 -->
                <text v-for="tick in yAxisTicks" :key="'y'+tick.label" :x="20" :y="tick.y" font-size="12" fill="#A0AEC0">{{ tick.label }}</text>
                
                <!-- 动态X轴标签 -->
                <text v-for="tick in xAxisTicks" :key="'x'+tick.label" :x="tick.x" y="215" font-size="12" fill="#A0AEC0">{{ tick.label }}</text>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ReloadOutlined } from '@ant-design/icons-vue'
import { storageApi } from '@/api'

// 响应式数据
const storageData = ref({
  capacity: '--',
  total: '--',
  available: '--',
  usagePercent: 0
})

const cpuData = ref({
  usage: '--',
  peak: '--',
  average: '--',
  usagePercent: 0
})

const backupData = ref({
  count: '0',
  full: '0',
  other: '0',
  progressPercent: 0
})

const notificationData = ref({
  count: '0',
  notice: '0',
  alert: '0',
  progressPercent: 0
})

// 字符串中提取数字（支持带单位如 GB、%）
const parseNumber = (val) => {
  if (val == null) return null
  if (typeof val === 'number') return val
  const m = String(val).match(/([0-9]+(?:\.[0-9]+)?)/)
  return m ? parseFloat(m[1]) : null
}

// ========================
// 趋势图（IOPS/吞吐量）数据与绘制
// ========================
const chartWidth = 700
const chartHeight = 220
const padding = { left: 50, right: 50, top: 10, bottom: 20 }
const iopsSeries = ref([])
const throughputSeries = ref([])
const timeSeries = ref([])
const iopsPath = ref('')
const throughputPath = ref('')
const throughputAreaPath = ref('')
const yAxisTicks = ref([])
const xAxisTicks = ref([])

const formatTimeLabel = (t) => {
  if (!t) return ''
  try {
    const d = new Date(t)
    if (!isNaN(d.getTime())) {
      return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    }
  } catch (_) {}
  const s = String(t)
  // 尝试从字符串中截取 HH:mm
  const m = s.match(/\b(\d{2}:\d{2})\b/)
  return m ? m[1] : s.slice(0, 5)
}

const getNiceMax = (maxVal) => {
  if (!maxVal || maxVal <= 0) return 100
  const pow = Math.pow(10, Math.floor(Math.log10(maxVal)))
  const norm = maxVal / pow
  let nice
  if (norm <= 1) nice = 1
  else if (norm <= 2) nice = 2
  else if (norm <= 5) nice = 5
  else nice = 10
  return nice * pow
}

const buildPaths = () => {
  const n = Math.max(iopsSeries.value.length, throughputSeries.value.length)
  if (n < 2) {
    // 数据不足，清空路径与坐标轴
    iopsPath.value = ''
    throughputPath.value = ''
    throughputAreaPath.value = ''
    yAxisTicks.value = []
    xAxisTicks.value = []
    return
  }
  const left = padding.left
  const right = padding.right
  const top = padding.top
  const bottom = padding.bottom
  const plotWidth = chartWidth - left - right
  const plotHeight = chartHeight - top - bottom

  const maxVal = getNiceMax(Math.max(
    Math.max(...iopsSeries.value.map(v => v || 0)),
    Math.max(...throughputSeries.value.map(v => v || 0))
  ))
  const xStep = plotWidth / (n - 1)
  const xPositions = Array.from({ length: n }, (_, i) => left + i * xStep)
  const toY = (v) => top + (plotHeight - (Math.min(v, maxVal) / maxVal) * plotHeight)

  // 生成平滑路径（Catmull-Rom 转换为三次 Bezier）
  const buildSmoothPath = (series) => {
    const pts = series.map((v, i) => [xPositions[i], toY(v || 0)])
    if (pts.length < 2) return ''
    if (pts.length === 2) return `M ${pts[0][0]} ${pts[0][1]} L ${pts[1][0]} ${pts[1][1]}`
    const t = 0.5 // 张力，0.5 更平滑且避免过度振荡
    let d = `M ${pts[0][0]} ${pts[0][1]}`
    for (let i = 0; i < pts.length - 1; i++) {
      const p0 = i > 0 ? pts[i - 1] : pts[i]
      const p1 = pts[i]
      const p2 = pts[i + 1]
      const p3 = i + 2 < pts.length ? pts[i + 2] : pts[i + 1]
      const cx1 = p1[0] + (p2[0] - p0[0]) / 6 * t
      const cy1 = p1[1] + (p2[1] - p0[1]) / 6 * t
      const cx2 = p2[0] - (p3[0] - p1[0]) / 6 * t
      const cy2 = p2[1] - (p3[1] - p1[1]) / 6 * t
      d += ` C ${cx1} ${cy1}, ${cx2} ${cy2}, ${p2[0]} ${p2[1]}`
    }
    return d
  }

  // IOPS线（平滑）
  iopsPath.value = buildSmoothPath(iopsSeries.value)
  // 吞吐量线（平滑）
  throughputPath.value = buildSmoothPath(throughputSeries.value)
  // 吞吐量填充区域（封闭路径）
  const firstX = xPositions[0]
  const lastX = xPositions[xPositions.length - 1]
  const baseY = top + plotHeight
  throughputAreaPath.value = buildSmoothPath(throughputSeries.value) + ` L ${lastX} ${baseY} L ${firstX} ${baseY} Z`

  // Y轴刻度（5段）
  const stepVal = maxVal / 4
  yAxisTicks.value = [4, 3, 2, 1, 0].map(k => ({
    y: top + (plotHeight - (k / 4) * plotHeight),
    label: Math.round(stepVal * k)
  }))
  // X轴刻度（5个点：首、25%、50%、75%、末）
  const idxs = [0, Math.round((n - 1) * 0.25), Math.round((n - 1) * 0.5), Math.round((n - 1) * 0.75), n - 1]
  xAxisTicks.value = idxs.map(i => ({ x: xPositions[i], label: formatTimeLabel(timeSeries.value[i]) }))
}

const fetchTrendData = async (limit = 1200) => {
  try {
    const resp = await storageApi.getStorageTrend({ limit })
    const list = Array.isArray(resp?.data) ? resp.data : (Array.isArray(resp) ? resp : (resp?.data?.records || []))
    if (!Array.isArray(list) || list.length === 0) {
      iopsSeries.value = []
      throughputSeries.value = []
      timeSeries.value = []
      buildPaths()
      return
    }

    const iops = []
    const thr = []
    const times = []
    for (const item of list) {
      // IOPS: 优先 iops，其次读写之和
      const iopsVal = parseNumber(
        item.iops ?? ((item.readOpsPerSec ?? item.readIops ?? 0) + (item.writeOpsPerSec ?? item.writeIops ?? 0))
      )
      // 吞吐量（MB/s）：优先 throughputMBps/throughput，其次读写之和
      const thrVal = parseNumber(
        item.throughputMBps ?? item.throughput ?? ((item.readMBps ?? item.readThroughputMBps ?? 0) + (item.writeMBps ?? item.writeThroughputMBps ?? 0))
      )
      const ts = item.timestamp ?? item.collectTime ?? item.time ?? item.createdAt ?? item.createTime
      iops.push(iopsVal ?? 0)
      thr.push(thrVal ?? 0)
      times.push(ts ?? '')
    }

    iopsSeries.value = iops
    throughputSeries.value = thr
    timeSeries.value = times
    buildPaths()
  } catch (e) {
    console.error('获取存储趋势失败:', e)
  }
}

const refreshTrend = () => {
  fetchTrendData(1200)
}

// 获取概览数据（联调 Metrics Controller 的四个接口）
const fetchOverviewData = async () => {
  try {
    const [storageInfo, cpuInfo, backupInfo, noticeInfo] = await Promise.all([
      storageApi.getStorageOverview(),       // POST /metrics/metrics-info
      storageApi.getCpuUsage(),              // POST /metrics/cpu-usage
      storageApi.getBackupInfo(),            // POST /metrics/backup-info
      storageApi.getPerformanceMetrics()     // POST /metrics/notice-info
    ])

    // 存储容量
    const total = storageInfo?.totalStorage ?? storageInfo?.total
    const free = storageInfo?.freeStorage ?? storageInfo?.available
    const used = storageInfo?.usedStorage ?? (total && free ? `${parseNumber(total) - parseNumber(free)}GB` : undefined)
    if (total) storageData.value.total = total
    if (free) storageData.value.available = free
    if (used) storageData.value.capacity = used
    const totalNum = parseNumber(storageData.value.total)
    const usedNum = parseNumber(storageData.value.capacity)
    if (totalNum && usedNum && totalNum > 0) {
      storageData.value.usagePercent = Math.round((usedNum / totalNum) * 100)
    }

    // CPU 使用率
    const usage = cpuInfo?.cpuUsage ?? cpuInfo?.usage
    const peak = cpuInfo?.cpuPeak ?? cpuInfo?.peak
    const avg = cpuInfo?.cpuAverage ?? cpuInfo?.average
    if (usage) cpuData.value.usage = typeof usage === 'string' ? usage : `${usage}%`
    if (peak) cpuData.value.peak = typeof peak === 'string' ? peak : `${peak}%`
    if (avg) cpuData.value.average = typeof avg === 'string' ? avg : `${avg}%`
    const usageNum = parseNumber(cpuData.value.usage)
    if (usageNum != null) cpuData.value.usagePercent = Math.round(usageNum)

    // 备份数据
    const count = backupInfo?.backupCount ?? backupInfo?.count
    const full = backupInfo?.fullBackup ?? backupInfo?.full
    const other = backupInfo?.otherBackup ?? backupInfo?.other
    backupData.value.count = String(parseNumber(count) ?? 0)
    backupData.value.full = String(parseNumber(full) ?? 0)
    backupData.value.other = String(parseNumber(other) ?? 0)
    const countNum = parseNumber(backupData.value.count)
    const fullNum = parseNumber(backupData.value.full)
    if (countNum && countNum > 0 && fullNum != null) {
      backupData.value.progressPercent = Math.min(100, Math.round((fullNum / countNum) * 100))
    } else {
      backupData.value.progressPercent = 0
    }

    // 通知告警（后端字段：notice=总数, noticeType=通知数, warningType=告警数）
    const noticeTotal = noticeInfo?.notice ?? 0
    const noticeCount = noticeInfo?.noticeType ?? 0
    const warningCount = noticeInfo?.warningType ?? 0
    notificationData.value.count = String(noticeTotal)        // 顶部应显示总数（例如 295）
    notificationData.value.notice = String(noticeCount)       // 通知：noticeType（例如 18）
    notificationData.value.alert = String(warningCount)       // 告警：warningType（例如 277）
    const totalNotice = parseNumber(notificationData.value.count)
    const warningNum = parseNumber(notificationData.value.alert)
    if (totalNotice && warningNum != null) {
      notificationData.value.progressPercent = Math.min(100, Math.round((warningNum / totalNotice) * 100))
    }

    // 数据联调完成
  } catch (error) {
    console.error('获取概览数据失败:', error)
  }
}

onMounted(() => {
  fetchOverviewData()
  fetchTrendData(1200)
})
</script>

<style scoped>
.storage-overview {
  padding: 0;
  background: transparent;
  color: #fff;
  margin-bottom: 24px;
}

.overview-header {
  margin-left: 1em;
  margin-top: 1em;
  margin-bottom:1em;
  opacity: 1;
  color: #FFFFFF;
  font-family: Source Han Sans;
  font-weight: bold;
  font-size: 18px;
  line-height: 22px;
  letter-spacing: 0px;
  text-align: left;
}

.overview-header h2 {
  color: #ffffff;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  font-family: 'Source Han Sans', sans-serif;
}

.stats-cards {
  margin-bottom: 24px;
  margin-right: 1em;
  margin-left: 1em;
}

.stat-card {
  background: #FFFFFF07;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  height: 125px;
  transition: all 0.3s ease;
  padding: 16px 20px;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.stat-card:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.stat-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  justify-content: space-between;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #00CFFD;
  margin: 0;
  line-height: 1;
  margin-bottom: 8px;
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #E0E6ED;
  margin: 0;
  font-weight: 400;
  margin-bottom: 8px;
  text-align: center;
}

.progress-bar {
  width: 100%;
  height: 4px;
  background: #FFFFFF33;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-fill {
  height: 100%;
  border-radius: 2px;
  transition: width 0.3s ease;
}

.storage-progress,
.cpu-progress,
.backup-progress,
.notification-progress {
  background: #4FCEFD;
}

.stat-detail {
  display: flex;
  gap: 16px;
  font-size: 12px;
  justify-content: space-between;
}

.detail-row {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 2px;
}

.detail-label {
  font-size: 12px;
  color: #A0AEC0;
  font-weight: 400;
}

/* 不同卡片的特殊样式 */
.storage-card .stat-value,
.cpu-card .stat-value,
.backup-card .stat-value,
.notification-card .stat-value {
  color: #00CFFD;
}

.chart-section {
  margin-top: 24px;
}

.chart-card {
  background: #FFFFFF0C;
  /* border: 1px solid rgba(255, 255, 255, 0.1); */
  /* border-radius: 10px; */
  padding: 1.5rem;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

.chart-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #00CFFD 0%, #0099cc 100%);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  color: #ffffff;
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  font-family: 'Source Han Sans', sans-serif;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.time-range {
  color: #9ca3af;
  font-size: 14px;
  padding: 4px 8px;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 4px;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.refresh-btn {
  color: #9ca3af !important;
  border: 1px solid rgba(59, 130, 246, 0.2) !important;
  background: rgba(59, 130, 246, 0.1) !important;
}

.refresh-btn:hover {
  color: #00CFFD !important;
  border-color: rgba(0, 212, 255, 0.5) !important;
  background: rgba(0, 212, 255, 0.1) !important;
}

.chart-container {
  width: 100%;
  height: 48em;
  min-height: 200px;
  max-height: 600px;
}

.chart-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-legend {
  display: flex;
  gap: 32px;
  margin-bottom: 20px;
  justify-content: center;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-dot {
  width: 12px;
  height: 12px;
  border-radius: 2px;
}

.legend-dot.iops {
  background: #FFFFFF;
}

.legend-dot.throughput {
  background: #00CFFD;
}

.legend-text {
  color: #E0E6ED;
  font-size: 14px;
  font-weight: 500;
}

.chart-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #1E293B;
  border-radius: 4px;
  padding: 1rem;
  min-height: 200px;
  overflow: hidden;
}

.performance-chart {
  width: 100%;
  height: 100%;
}
</style>